package com.magicode.portal.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.persistence.Entity;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;

import org.apache.commons.lang.StringEscapeUtils;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.magicode.cms.entiy.base.Attitude;
import com.magicode.cms.entiy.base.Dictionary;
import com.magicode.cms.entiy.base.News;
import com.magicode.cms.entiy.base.User;
import com.magicode.cms.entiy.base.WebSiteBase;
import com.magicode.cms.entiy.base.WsbeComment;
import com.magicode.cms.entiy.base.WsbeCommentItem;
import com.magicode.common.dao.ICommonDaoService;
import com.magicode.common.dao.PageResults;
import com.magicode.portal.service.IWebCommentService;

@Service("webCommentService")
@Transactional
public class WebCommentServiceImpl implements IWebCommentService {

	@Autowired
	@Qualifier("commonDaoService")
	private ICommonDaoService commonDaoService;

	@Override
	public PageResults listByNewsId(String className,String id, Integer pageNo, Integer pageSize) {
		String hql = " from com.magicode.cms.entiy.base.WsbeCommentItem t " //com.magicode.cms.entiy.base.NewsComment
				+ " left join fetch t.author "
				+ " left join fetch t.author.mainPic "
				+ " where t.wsbe.entityClassName=? and t.wsbe.wsbeId=? "
				+ " order by t.createTime desc";
		PageResults pageResults = commonDaoService.findPageByFetchedHql(hql, null, pageNo==null?1:pageNo, pageSize, new String[]{className,id});
		return pageResults;
	}

	/**
	 * 我接收到的评论
	 */
	@Override
	public PageResults myReceiveListByUserId(String className,String userId, Integer pageNo, Integer pageSize) {
 		String hql = " from com.magicode.cms.entiy.base.WsbeCommentItem t "
				+ " left join fetch t.author "
				+ " left join fetch t.author.mainPic "
				+ " left join fetch t.replyComment" 
				+ " left join fetch t.replyComment.author "
				+ " where t.wsbe.entityClassName=? and t.replyComment.author.id=? "
				+ " order by t.createTime desc";
		PageResults pageResults = commonDaoService.findPageByFetchedHql(hql, null, pageNo==null?1:pageNo, pageSize, new String[]{className,userId});
		return pageResults;
	}
	/**
	 * 我发出到的评论
	 */
	@Override
	public PageResults mySendListByUserId(String className,String userId, Integer pageNo, Integer pageSize) {
		String hql = " from com.magicode.cms.entiy.base.WsbeCommentItem t "
				+ " left join fetch t.author "
				+ " left join fetch t.author.mainPic "
				+ " left join fetch t.replyComment "
				+" left join fetch t.replyComment.author "
				+ " where t.wsbe.entityClassName=? and t.author.id=? "
				+ " order by t.createTime desc";
		PageResults pageResults = commonDaoService.findPageByFetchedHql(hql, null, pageNo==null?1:pageNo, pageSize, new String[]{className,userId});
		return pageResults;
	}
	
	
	@Override
	public WsbeCommentItem createByNewsId(HttpSession session, String entityClassName, String newsId, User user, String text) throws UnsupportedEncodingException {
		WsbeCommentItem comment = null;
		WsbeComment news = (WsbeComment) this.getWsbeComment(newsId);
		if(null==news){
			news=new  WsbeComment();
		}
		if(news.getId() == null){
			news.setEntityClassName(entityClassName);
			news.setCreateTime(new Date());
			news.setCommentsCount(new Long(0));
			news.setClientType(2);
			news.setWsbeId(newsId);
			this.commonDaoService.save(news);
			
		}
		if(null==comment){
			comment=new WsbeCommentItem();
			if(user != null){
				comment.setAuthor(user);
			}else{
				comment.setGuestName(this.getGuestName(session));
			}
			comment.setWsbe(news);
//			String ss=StringEscapeUtils.escapeHtml(text);
//			byte[] s=StringEscapeUtils.escapeHtml(text).getBytes("UTF-8");
			comment.setText(StringEscapeUtils.escapeHtml(text).getBytes("UTF-8"));
			comment.setCreateTime(new Date());
			this.commonDaoService.merge(comment);
		}
		Long size=this.getsize(newsId);
		news.setCommentsCount(size);
		this.commonDaoService.update(news);
		try {
			Class cl = Class.forName(entityClassName);
			Object object = cl.newInstance();
			if(cl.getSuperclass().getName().equals(News.class.getName())){
				News siteBase =(News) this.commonDaoService.get(News.class, newsId);
				siteBase.setCommentsCount(size);
				this.commonDaoService.update(siteBase);
			}
			if(cl.getSuperclass().getName().equals(WebSiteBase.class.getName())){
				String classTable = "";
				if (cl.isAnnotationPresent(Entity.class)) { //是否Entity
					Entity entity = (Entity) cl.getAnnotation(Entity.class);
					classTable=entity.name();		
				}
				String Sql=" update "+classTable+" set comments_count="+size+" where id='"+newsId+"' ";
				this.commonDaoService.querySql(Sql, null);	
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return comment;
	}

	@Override
	public WsbeCommentItem replyByCommentId(HttpSession session, String commentId, String newsId, User user, String text, String type) throws UnsupportedEncodingException {
		WsbeCommentItem reply = new WsbeCommentItem();
		WsbeCommentItem comment = new WsbeCommentItem();
		comment.setId(commentId);
		WsbeComment news = (WsbeComment) this.getWsbeComment(newsId);
		news.setCommentsCount(news.getCommentsCount()+1);
		this.commonDaoService.update(news);
		String entityName=news.getEntityClassName();
		try {
			Class cl = Class.forName(entityName);
			Object object = cl.newInstance();
			if(cl.getSuperclass().getName().equals(News.class.getName())){
				News siteBase =(News) this.commonDaoService.get(News.class, newsId);
				siteBase.setCommentsCount(news.getCommentsCount());
				this.commonDaoService.update(siteBase);
			}
			if(cl.getSuperclass().getName().equals(WebSiteBase.class.getName())){
				String classTable = "";
				if (cl.isAnnotationPresent(Entity.class)) { //是否Entity
					Entity entity = (Entity) cl.getAnnotation(Entity.class);
					classTable=entity.name();		
				}
				String Sql=" update "+classTable+" set comments_count="+news.getCommentsCount();
				this.commonDaoService.querySql(Sql, null);	
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(user != null){
			reply.setAuthor(user);
		}else{
			reply.setGuestName(this.getGuestName(session));
		}
		reply.setAuthor(user);
		reply.setWsbe(news);
		reply.setReplyComment(comment);
		if(text!=null){
			reply.setText(text.getBytes("UTF-8"));
		}
		reply.setCreateTime(new Date());
		reply = (WsbeCommentItem) this.commonDaoService.merge(reply);
		if(null!=reply.getAuthor()){
			Hibernate.initialize(reply.getAuthor());
			Hibernate.initialize(reply.getAuthor().getMainPic());
		}
		Hibernate.initialize(reply.getWsbe());
//		String hql = " from com.magicode.cms.entiy.base.NewsComment t left join fetch t.author join fetch t.news where t.id=?";
//		reply = (NewsComment) this.commonDaoService.getByHQL(hql, reply.getId());
		return reply;
	}

	@Override
	public Attitude addAttitude(HttpSession session, String commentId, String newsId, User user, String text, String type) throws UnsupportedEncodingException {
		Attitude attitude = new Attitude();
		String hql = " from com.magicode.cms.entiy.base.Dictionary t where 1=1 ";
		if("zan".equals(type))
			hql += " and t.code='Zan' ";
		else
			hql += " and t.code='Cai' ";
//			+ "t.type='AttitudeType' ";//暂不支持
		if(commentId!=null && commentId.length()>0 && !"null".equals(commentId)){//commentId不为空时，表示该赞和踩是针对评论的
			WsbeCommentItem comment = (WsbeCommentItem) this.commonDaoService.get(WsbeCommentItem.class, commentId);
			//更新赞和踩的个数
			if("zan".equals(type)){
				if(comment.getAttZan()!=null)
					comment.setAttZan(comment.getAttZan()+1);
				else
					comment.setAttZan(1);
			}else{
				if(comment.getAttCai()!=null)
					comment.setAttCai(comment.getAttCai()+1);
				else
					comment.setAttCai(1);
			}
			this.commonDaoService.update(comment);
		//	attitude.setNewsComments(comment);//新闻评论
		}else if(commentId!=null && "null".equals(commentId) && newsId!=null && newsId.length()>0){//newsId不为空时，表示该赞和踩是针对文章的
			WsbeComment news = (WsbeComment) this.getWsbeComment(newsId);
			//更新赞和踩的个数
//			if("zan".equals(type)){
//				if(news.getEntityClassName().getAttZan()!=null)
//					news.setAttZan(news.getEntityClassName().getAttZan()+1);
//				else
//					news.setAttZan(1);
//			}else{
//				if(news.getEntityClassName().getAttCai()!=null)
//					news.setAttCai(news.getEntityClassName().getAttCai()+1);
//				else
//					news.setAttCai(1);
//			}
			this.commonDaoService.update(news);
		//	attitude.setNews(news);
		}
		if(user != null){
			attitude.setAuthor(user);
		}else{
			attitude.setGuestName(this.getGuestName(session));
		}
		Dictionary dictionary = (Dictionary) this.commonDaoService.getByHQL(hql, null);
		attitude.setAuthor(user);
		attitude.setType(dictionary);
		attitude.setCreateTime(new Date());
		attitude = (Attitude) this.commonDaoService.merge(attitude);
		return attitude;
	}
	
	private String getGuestName(HttpSession session){
		String guest_name = (String) session.getAttribute("guest_name");
		if(guest_name!=null){
			return guest_name;
		}else{
			guest_name = "传媒人";
			Random random = new Random();
			guest_name = guest_name + random.nextInt(9999);
			session.setAttribute("guest_name", guest_name);
			return guest_name;
		}
	}

	@Override
	@Transactional
	public void deleteCommetById(String commentid) { 
		WsbeCommentItem obj = (WsbeCommentItem) commonDaoService.get(WsbeCommentItem.class, commentid);
		if(null!=obj){
			try {
				commonDaoService.delete(obj);
				WsbeComment news = (WsbeComment) this.commonDaoService.get(WsbeComment.class, obj.getWsbe().getId());
				news.setCommentsCount(news.getCommentsCount()-1-obj.getRelateReplyCommonts().size());
				this.commonDaoService.update(news);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	}

	@Override
	public Long getUserComment(String userid) {
		String hql = " select count(t.id) from "+WsbeCommentItem.class.getName()+" t where t.author.id='"+userid+"'";
		return commonDaoService.countByHqlMap(hql, null);
	}

	@Override
	public Long getsize(String newsId) {
		String hql="select count(t.id) from "+WsbeCommentItem.class.getName()+" t where t.wsbe.wsbeId='"+newsId+"'";
		return commonDaoService.countByHqlMap(hql, null);
	}
	
	
	@Override
	public WsbeComment getWsbeComment(String newsId) {
		String hql = " from "+WsbeComment.class.getName()+" t where t.wsbeId='"+newsId+"'";
		return (WsbeComment) commonDaoService.getByHQL(hql,null);
	}
	
	@Override
	public WsbeCommentItem getWsbeCommentItem(String newsId) {
		String hql = " from "+WsbeCommentItem.class.getName()+" t where t.wsbe.wsbeId='"+newsId+"'";
		return (WsbeCommentItem) commonDaoService.getByHQL(hql,null);
	}
}
